package kr.or.kosta.otr.controller.companycontroller;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import kr.or.kosta.otr.service.companyservice.CompanyService;
import kr.or.kosta.otr.utill.CompanyListVO;
import kr.or.kosta.otr.utill.ValueComparator;
import kr.or.kosta.otr.vo.CompanyReviewVO;
import kr.or.kosta.otr.vo.CompanyVO;
import kr.or.kosta.otr.vo.IndustryVO;
import kr.or.kosta.otr.vo.RegionVO;
import kr.or.kosta.otr.vo.ReportVO;
import kr.or.kosta.otr.vo.UserVO;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class CompanyController {
	@Resource(name = "CompanyService")
	CompanyService companyService;

	@RequestMapping(value = "/searchCompanyByName.action")
	public ModelAndView searchCompanyByName(
			@RequestParam(value = "companyName") String companyName)
					throws SQLException {
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("company", "company_name");
		map.put("companyValue", companyName);
		ArrayList<CompanyVO> clist = companyService.getCompanyInfo(map);
		if (!clist.isEmpty()) {
			for(CompanyVO vo : clist){
				double temp = vo.getCompanyTotalScore();
				vo.setCompanyTotalScore(Math.round(temp * 100)/100.0);
			}
		}
		ModelAndView mv = getListIndustryAndRegion();
		mv.addObject("clist", clist);
		return mv;
	}	

	@RequestMapping(value = "/searchCompanyByName2.action")
	public ModelAndView searchCompanyByName2(
			@RequestParam(value = "companyName") String companyName)
					throws SQLException {
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("company", "company_name");
		map.put("companyValue", companyName);

		ArrayList<CompanyVO> clist = companyService.getCompanyInfo(map);
		ArrayList<String> cnameList=new ArrayList<String>();

		if (clist.isEmpty()) {
			clist = null;
		}
		for(CompanyVO vo:clist){
			cnameList.add(vo.getCompanyName());
		}

		return new ModelAndView("JsonView", "cnameList", cnameList);
	}

	@RequestMapping(value = "/getListIndustryAndRegion.action")
	public ModelAndView getListIndustryAndRegion() throws SQLException {

		ArrayList<IndustryVO> ilist = companyService.getAllIndustry();
		ArrayList<RegionVO> rlist = companyService.getAllRegion();

		ModelAndView mv = new ModelAndView("company/company_search");
		mv.addObject("ilist", ilist);
		mv.addObject("rlist", rlist);

		return mv;
	}

	@RequestMapping(value = "/getCompanyByIndustryName.action")
	public ModelAndView getCompanyByIndustryName(
			@RequestParam(value = "industryName") String industryName,@RequestParam(value="pageNo")String pageNo)
					throws SQLException {

		String flag = "industry";

		HashMap<String, Object> tmap = new HashMap<String, Object>();

		tmap.put("company", "industry_name");
		tmap.put("companyValue", industryName);

		HashMap<String, Object> map = new HashMap<String, Object>();

		map.put("company", "industry_name");
		map.put("companyValue", industryName);
		map.put("value", pageNo);
		ArrayList<CompanyVO> clist = companyService.getCompanyInfo(map);
		CompanyListVO cclist =companyService.getCompanyInfoPage(map, tmap);
		ModelAndView mv = getListIndustryAndRegion();
		mv.addObject("name", industryName);
		mv.addObject("cclist", cclist);
		mv.addObject("clist", clist);
		mv.addObject("flag", flag);

		return mv;
	}

	@RequestMapping(value = "/getCompanyByRegionName.action")
	public ModelAndView getCompanyByRegionName(
			@RequestParam(value = "regionName") String regionName,@RequestParam(value="pageNo")String pageNo)
					throws SQLException {

		String flag = "region";

		HashMap<String, Object> tmap = new HashMap<String, Object>();

		tmap.put("company", "region_name");
		tmap.put("companyValue", regionName);

		HashMap<String, Object> map = new HashMap<String, Object>();

		map.put("company", "region_name");
		map.put("companyValue", regionName);
		map.put("value", pageNo);
		ArrayList<CompanyVO> clist = companyService.getCompanyInfo(map);
		CompanyListVO cclist =companyService.getCompanyInfoPage(map, tmap);
		ModelAndView mv = getListIndustryAndRegion();
		mv.addObject("name", regionName);
		mv.addObject("clist", clist);
		mv.addObject("cclist", cclist);
		mv.addObject("flag", flag);

		return mv;
	}

	@RequestMapping(value = "/getCompanyByTotalScore.action")
	public ModelAndView getCompanyByTotalScore(@RequestParam(value="pageNo")String pageNo) throws SQLException {
		String flag = "score";

		// companyId 받아오기
		ArrayList<CompanyReviewVO> crList = companyService
				.getAllCompanyReview();

		HashMap<Integer, Float> map = new HashMap<Integer, Float>();
		for (int i = 0; i < crList.size(); i++) {
			int companyId = crList.get(i).getCompanyVo().getCompanyId();
			float scoreChance = companyService.getTotalScoreOfTotal(companyId);
			map.put(companyId, scoreChance);

		}

		// 이 숫자 나열하기
		ValueComparator vc = new ValueComparator(map);
		TreeMap<Integer, Float> sortMap = new TreeMap<Integer, Float>(vc);

		sortMap.putAll(map);

		// company 입력하기
		ArrayList<CompanyVO> clist = new ArrayList<CompanyVO>();
		for (Integer companyId : sortMap.keySet()) {
			clist.add(companyService.getOneCompany(companyId));
		}

		//page
		int page =1;
		if(pageNo != null){
			page = Integer.parseInt(pageNo);
		}

		ArrayList<CompanyVO> cclist = new ArrayList<CompanyVO>();
		int start = (page - 1) * 6;
		int end = page * 6 - 1;
		if(end > clist.size())
			end = clist.size()-1;
		for(int i =start; i<=end;i++)
			cclist.add(clist.get(i));

		double total=Math.ceil(clist.size()/6.0);
		ModelAndView mv = getListIndustryAndRegion();
		mv.addObject("name","getCompanyByTotalScore.action");
		mv.addObject("page",total);
		mv.addObject("nowPage", pageNo);
		mv.addObject("cclist",cclist);
		mv.addObject("clist", clist);
		mv.addObject("flag", flag);

		return mv;
	}

	@RequestMapping(value = "/getCompanyByScoreChance.action")
	public ModelAndView getCompanyByScoreChance(@RequestParam(value="pageNo")String pageNo) throws SQLException {
		String flag = "score";

		// companyId 받아오기
		ArrayList<CompanyReviewVO> crList = companyService
				.getAllCompanyReview();

		HashMap<Integer, Float> map = new HashMap<Integer, Float>();
		for (int i = 0; i < crList.size(); i++) {
			int companyId = crList.get(i).getCompanyVo().getCompanyId();
			float scoreChance = companyService.getTotalScoreOfChance(companyId);
			map.put(companyId, scoreChance);

		}

		// 이 숫자 나열하기
		ValueComparator vc = new ValueComparator(map);
		TreeMap<Integer, Float> sortMap = new TreeMap<Integer, Float>(vc);

		sortMap.putAll(map);

		// company 입력하기
		ArrayList<CompanyVO> clist = new ArrayList<CompanyVO>();
		for (Integer companyId : sortMap.keySet()) {
			clist.add(companyService.getOneCompany(companyId));
		}
		//page
		int page =1;
		if(pageNo != null){
			page = Integer.parseInt(pageNo);
		}

		ArrayList<CompanyVO> cclist = new ArrayList<CompanyVO>();
		int start = (page - 1) * 6;
		int end = page * 6 - 1;
		if(end > clist.size())
			end = clist.size()-1;
		for(int i =start; i<=end;i++)
			cclist.add(clist.get(i));

		double total=Math.ceil(clist.size()/6.0);
		ModelAndView mv = getListIndustryAndRegion();
		mv.addObject("name","getCompanyByScoreChance.action");
		mv.addObject("page",total);
		mv.addObject("nowPage", pageNo);
		mv.addObject("cclist",cclist);
		mv.addObject("clist", clist);
		mv.addObject("flag", flag);

		return mv;

	}

	@RequestMapping(value = "/getCompanyByScoreWelfare.action")
	public ModelAndView getCompanyByScoreWelfare(@RequestParam(value="pageNo")String pageNo) throws SQLException {
		String flag = "score";

		// companyId 받아오기
		ArrayList<CompanyReviewVO> crList = companyService
				.getAllCompanyReview();

		HashMap<Integer, Float> map = new HashMap<Integer, Float>();
		for (int i = 0; i < crList.size(); i++) {
			int companyId = crList.get(i).getCompanyVo().getCompanyId();
			float scoreChance = companyService
					.getTotalScoreOfWelfare(companyId);
			map.put(companyId, scoreChance);

		}

		// 이 숫자 나열하기
		ValueComparator vc = new ValueComparator(map);
		TreeMap<Integer, Float> sortMap = new TreeMap<Integer, Float>(vc);

		sortMap.putAll(map);


		// company 입력하기
		ArrayList<CompanyVO> clist = new ArrayList<CompanyVO>();
		for (Integer companyId : sortMap.keySet()) {
			clist.add(companyService.getOneCompany(companyId));
		}
		//page
		int page =1;
		if(pageNo != null){
			page = Integer.parseInt(pageNo);
		}

		ArrayList<CompanyVO> cclist = new ArrayList<CompanyVO>();
		int start = (page - 1) * 6;
		int end = page * 6 - 1;
		if(end > clist.size())
			end = clist.size()-1;
		for(int i =start; i<=end;i++)
			cclist.add(clist.get(i));

		double total=Math.ceil(clist.size()/6.0);
		ModelAndView mv = getListIndustryAndRegion();
		mv.addObject("name","getCompanyByScoreWelfare.action");
		mv.addObject("page",total);
		mv.addObject("nowPage", pageNo);
		mv.addObject("cclist",cclist);
		mv.addObject("clist", clist);
		mv.addObject("flag", flag);

		return mv;
	}

	@RequestMapping(value = "/getCompanyByScoreOverdue.action")
	public ModelAndView getCompanyByScoreOverdue(@RequestParam(value="pageNo")String pageNo) throws SQLException {
		String flag = "score";

		// companyId 받아오기
		ArrayList<CompanyReviewVO> crList = companyService
				.getAllCompanyReview();

		HashMap<Integer, Float> map = new HashMap<Integer, Float>();
		for (int i = 0; i < crList.size(); i++) {
			int companyId = crList.get(i).getCompanyVo().getCompanyId();
			float scoreChance = companyService
					.getTotalScoreOfOverdue(companyId);
			map.put(companyId, scoreChance);

		}

		// 이 숫자 나열하기
		ValueComparator vc = new ValueComparator(map);
		TreeMap<Integer, Float> sortMap = new TreeMap<Integer, Float>(vc);

		sortMap.putAll(map);

		// company 입력하기
		ArrayList<CompanyVO> clist = new ArrayList<CompanyVO>();
		for (Integer companyId : sortMap.keySet()) {
			clist.add(companyService.getOneCompany(companyId));
		}
		//page
		int page =1;
		if(pageNo != null){
			page = Integer.parseInt(pageNo);
		}

		ArrayList<CompanyVO> cclist = new ArrayList<CompanyVO>();
		int start = (page - 1) * 6;
		int end = page * 6 - 1;
		if(end > clist.size())
			end = clist.size()-1;
		for(int i =start; i<=end;i++)
			cclist.add(clist.get(i));

		double total=Math.ceil(clist.size()/6.0);
		ModelAndView mv = getListIndustryAndRegion();
		mv.addObject("name","getCompanyByScoreOverdue.action");
		mv.addObject("page",total);
		mv.addObject("nowPage", pageNo);
		mv.addObject("cclist",cclist);
		mv.addObject("clist", clist);
		mv.addObject("flag", flag);

		return mv;

	}

	@RequestMapping(value = "/getCompanyByScoreHoliday.action")
	public ModelAndView getCompanyByScoreHoliday(@RequestParam(value="pageNo")String pageNo) throws SQLException {
		String flag = "score";

		// companyId 받아오기
		ArrayList<CompanyReviewVO> crList = companyService
				.getAllCompanyReview();

		HashMap<Integer, Float> map = new HashMap<Integer, Float>();
		for (int i = 0; i < crList.size(); i++) {
			int companyId = crList.get(i).getCompanyVo().getCompanyId();
			float scoreChance = companyService
					.getTotalScoreOfHoliday(companyId);
			map.put(companyId, scoreChance);

		}

		// 이 숫자 나열하기
		ValueComparator vc = new ValueComparator(map);
		TreeMap<Integer, Float> sortMap = new TreeMap<Integer, Float>(vc);

		sortMap.putAll(map);

		// company 입력하기
		ArrayList<CompanyVO> clist = new ArrayList<CompanyVO>();
		for (Integer companyId : sortMap.keySet()) {
			clist.add(companyService.getOneCompany(companyId));
		}
		//page
		int page =1;
		if(pageNo != null){
			page = Integer.parseInt(pageNo);
		}

		ArrayList<CompanyVO> cclist = new ArrayList<CompanyVO>();
		int start = (page - 1) * 6;
		int end = page * 6 - 1;
		if(end > clist.size())
			end = clist.size()-1;
		for(int i =start; i<=end;i++)
			cclist.add(clist.get(i));

		double total=Math.ceil(clist.size()/6.0);
		ModelAndView mv = getListIndustryAndRegion();
		mv.addObject("name","getCompanyByScoreHoliday.action");
		mv.addObject("page",total);
		mv.addObject("nowPage", pageNo);
		mv.addObject("cclist",cclist);
		mv.addObject("clist", clist);
		mv.addObject("flag", flag);

		return mv;

	}

	@RequestMapping(value = "/getCompanyByScoreCulture.action")
	public ModelAndView getCompanyByScoreCulture(@RequestParam(value="pageNo")String pageNo) throws SQLException {
		String flag = "score";

		// companyId 받아오기
		ArrayList<CompanyReviewVO> crList = companyService
				.getAllCompanyReview();

		HashMap<Integer, Float> map = new HashMap<Integer, Float>();
		for (int i = 0; i < crList.size(); i++) {
			int companyId = crList.get(i).getCompanyVo().getCompanyId();
			float scoreChance = companyService
					.getTotalScoreOfCulture(companyId);
			map.put(companyId, scoreChance);

		}

		// 이 숫자 나열하기
		ValueComparator vc = new ValueComparator(map);
		TreeMap<Integer, Float> sortMap = new TreeMap<Integer, Float>(vc);

		sortMap.putAll(map);

		// company 입력하기
		ArrayList<CompanyVO> clist = new ArrayList<CompanyVO>();
		for (Integer companyId : sortMap.keySet()) {
			clist.add(companyService.getOneCompany(companyId));
		}

		//page
		int page =1;
		if(pageNo != null){
			page = Integer.parseInt(pageNo);
		}

		ArrayList<CompanyVO> cclist = new ArrayList<CompanyVO>();
		int start = (page - 1) * 6;
		int end = page * 6 - 1;
		if(end > clist.size())
			end = clist.size()-1;
		for(int i =start; i<=end;i++)
			cclist.add(clist.get(i));

		double total=Math.ceil(clist.size()/6.0);
		ModelAndView mv = getListIndustryAndRegion();
		mv.addObject("name","getCompanyByScoreCulture.action");
		mv.addObject("page",total);
		mv.addObject("nowPage", pageNo);
		mv.addObject("cclist",cclist);
		mv.addObject("clist", clist);
		mv.addObject("flag", flag);

		return mv;

	}

	@RequestMapping(value = "/getCompanyByScoreExecutive.action")
	public ModelAndView getCompanyByScoreExecutive(@RequestParam(value="pageNo")String pageNo) throws SQLException {
		String flag = "score";

		// companyId 받아오기
		ArrayList<CompanyReviewVO> crList = companyService
				.getAllCompanyReview();

		HashMap<Integer, Float> map = new HashMap<Integer, Float>();
		for (int i = 0; i < crList.size(); i++) {
			int companyId = crList.get(i).getCompanyVo().getCompanyId();
			float scoreChance = companyService
					.getTotalScoreOfExecutive(companyId);
			map.put(companyId, scoreChance);

		}

		// 이 숫자 나열하기
		ValueComparator vc = new ValueComparator(map);
		TreeMap<Integer, Float> sortMap = new TreeMap<Integer, Float>(vc);

		sortMap.putAll(map);

		// company 입력하기
		ArrayList<CompanyVO> clist = new ArrayList<CompanyVO>();
		for (Integer companyId : sortMap.keySet()) {
			clist.add(companyService.getOneCompany(companyId));
		}

		//page
		int page =1;
		if(pageNo != null){
			page = Integer.parseInt(pageNo);
		}

		ArrayList<CompanyVO> cclist = new ArrayList<CompanyVO>();
		int start = (page - 1) * 6;
		int end = page * 6 - 1;
		if(end > clist.size())
			end = clist.size()-1;
		for(int i =start; i<=end;i++)
			cclist.add(clist.get(i));

		double total=Math.ceil(clist.size()/6.0);
		ModelAndView mv = getListIndustryAndRegion();
		mv.addObject("name","getCompanyByScoreExecutive.action");
		mv.addObject("page",total);
		mv.addObject("nowPage", pageNo);
		mv.addObject("cclist",cclist);
		mv.addObject("clist", clist);
		mv.addObject("flag", flag);

		return mv;
	}

	@RequestMapping(value = "/customCompanyList.action")
	public ModelAndView customCompanyList() throws SQLException {
		HashMap<String, ArrayList> map = new HashMap<String, ArrayList>();

		ArrayList<IndustryVO> industryList = companyService.getAllIndustry();
		ArrayList<RegionVO> regionList = companyService.getAllRegion();

		map.put("industryList", industryList);
		map.put("regionList", regionList);

		return new ModelAndView("company/custom_company_search", "listMap", map);
	}

	@RequestMapping(value = "/customCompany.action")
	public ModelAndView customCompany(
			@RequestParam(value = "industryName") String industryName,
			@RequestParam(value = "regionName") String regionName,
			@RequestParam(value = "companySalary") int companySalary,
			@RequestParam(value = "select1") String select1,
			@RequestParam(value = "select2") String select2,
			@RequestParam(value = "select3") String select3,HttpServletRequest request)
					throws SQLException {

		String score1 = request.getParameter("score");
		ModelAndView mav = new ModelAndView();
		int score;
		//score값이 없을 시 0 초기화
		if(score1 == null || score1.equals(null)){
			score = 0;
		}else
			score = Integer.parseInt(score1);
		HashMap<String, Object> map = new HashMap<String, Object>();
		if (industryName != null)
			map.put("industryName", industryName);
		if (regionName != null)
			map.put("regionName", regionName);
		if (companySalary != 0)
			map.put("companySalary", companySalary);

		// 조건에 맞는 회사 가져오기
		ArrayList<CompanyVO> com = companyService.customCompany(map);

		//company 담을 map
		ArrayList<CompanyVO> clist = new ArrayList<CompanyVO>();

		if(com.size() != 0){
			String[] scores = {"scoreChance","scoreWelfare","scoreCulture","scoreHoliday","scoreExecutive","scoreOverdue"};
			float[] scorei = new float[6];
			// 회사별 스코어 평균
			for (CompanyVO c : com) {
				int isExist = companyService.isExistCompanyReviewVerifyByCompanyId(c.getCompanyId());

				if (isExist != 0) {
					scorei[0] = companyService.getTotalScoreOfChance(c.getCompanyId());
					scorei[1] = companyService.getTotalScoreOfWelfare(c.getCompanyId());
					scorei[2] = companyService.getTotalScoreOfCulture(c.getCompanyId());
					scorei[3] = companyService.getTotalScoreOfHoliday(c.getCompanyId());
					scorei[4] = companyService.getTotalScoreOfExecutive(c.getCompanyId());
					scorei[5] = companyService.getTotalScoreOfOverdue(c.getCompanyId());
					if(scorei[0] != 0){
						double s1 =0;
						double s2 =0;
						double s3 =0;
						for(int i=0; i<scores.length; i++){
							if(select1.equals(scores[i])){
								s1 = Math.round(scorei[i] *100)/100.0; // 1순위 select 값 저장
								scorei[i] = (float) (scorei[i]+0.8);
							}else if(select2.equals(scores[i])){
								s2 = Math.round(scorei[i] *100)/100.0; // 2순위 select 값 저장
								scorei[i] = (float) (scorei[i]+0.5);
							}else if(select3.equals(scores[i])){
								s3 = Math.round(scorei[i] *100)/100.0; // 3순위 select 값 저장
								scorei[i] = (float) (scorei[i]+0.4);
							}
						}
						float scoreTotal = (scorei[0] + scorei[1] + scorei[2]
								+ scorei[3] + scorei[4] + scorei[5]) / 6;

						//score보다 높은 평점 넣기
						if(score <= scoreTotal){
							CompanyVO company =  companyService.getOneCompany(c.getCompanyId());
							double total = Math.round(scoreTotal *100)/100.0;
							if(total >= 5)
								total = 5.00;
							company.setCompanyTotalScore(total); // 평균값  담아둔다.
							company.setSelect1(s1); // 1순위 select 값 company 세팅
							company.setSelect2(s2); // 2순위 select 값 company 세팅
							company.setSelect3(s3); // 3순위 select 값 company 세팅
							clist.add(company);
						}

						mav.setViewName("company/custom_company_search");
					}
				}else{

					String error = "custom";
					mav.addObject("error",error);
					mav.setViewName("error");
					return mav;
				}
			}

			mav.addObject("clist",clist);
			mav.addObject("select1", select1);
			mav.addObject("select2", select2);
			mav.addObject("select3", select3);

			Collections.sort(clist,new Comparator<CompanyVO>() { // ArrayList 정렬
				@Override
				public int compare(CompanyVO o1, CompanyVO o2) {
					// TODO Auto-generated method stub
					return o1.getCompanyTotalScore() > o2.getCompanyTotalScore() ? -1 :(o1.getCompanyTotalScore() == o2.getCompanyTotalScore() ? 0: 1);
				}
			});

			ArrayList<CompanyVO> sclist= new ArrayList<CompanyVO>(); // 3위 까지 담는다
			sclist.add(clist.get(0));
			sclist.add(clist.get(1));
			sclist.add(clist.get(2));
			mav.addObject("sclist",sclist);


			return mav;
		}
		return new ModelAndView("company/custom_company_search");
	}

	@RequestMapping(value = "/reportCompanyRegister.action")
	public ModelAndView reportCompanyRegister(
			@RequestParam(value="companyName") String companyName,
			HttpSession session) throws SQLException {

		UserVO userVo = (UserVO) session.getAttribute("userVo");
		String message = "로그인 후 신청해 주세요!";
		if(userVo != null){
			ReportVO rvo = new ReportVO(userVo.getAdminVo(), userVo.getUserId(), null, companyName + " 회사 등록 요청!");
			companyService.writeReport(rvo);

			message = "등록 요청이 완료되었습니다.";

		}

		return new ModelAndView("JsonView","message", message);
	}
}
